﻿using System;
using System.Linq;
using System.Text;
using System.Data;
using System.Threading.Tasks;
using System.Collections.Generic;
using Kingdee.BOS.Util;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Core.Metadata.StateTracker;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.Metadata;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Core.Const;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.BarElement;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args.UnitTest;
using Kingdee.BOS;
using Kingdee.BOS.Contracts;


namespace Sincetech.K3.SCM.Common
{
    /// <summary>
    ///  库存业务单据：单据插件
    ///  采购入库单、采购退料单
    ///  销售出库单、销售退货单
    ///  初始库存、分布式调出、分布式调入、简单生产领料、简单生产入库、简单生产退料、盘亏单、盘盈单、批号调整单、其他出库单、其他入库单
    /// </summary>
    public class Stock_Bill : AbstractDynamicFormPlugIn
    {
        //物料编码
        string strValue = "";
        //物料代码
        string F_st_MaterialNo = "";
        //行号
        int F_st_RowNo = 0;
        //总双数
        int Ptotal = 0;

        #region 值更新事件
        /// <summary>
        /// 值更新事件-批号合并
        /// </summary>
        /// <param name="e"></param>
        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);
            #region 库存单据扩展-批号合并

            switch (e.Field.Key.ToUpper().ToString())
            {
                case "F_ST_SALEORDERBILLNO":       //销售单号             
                case "F_ST_PURORDERBILLNO":        //采购单号
                case "F_ST_SPROWNO":               //购销行号
                case "F_ST_SUPPLYID":              //供应商名称
                case "F_ST_ORIGINALBATCH":         //原批次
                    string F_ST_SALEORDERBILLNO = this.View.Model.GetValue("F_ST_SALEORDERBILLNO", e.Row) == null ? "" : this.View.Model.GetValue("F_ST_SALEORDERBILLNO", e.Row).ToString();
                    string F_ST_PURORDERBILLNO = this.View.Model.GetValue("F_ST_PURORDERBILLNO", e.Row) == null ? "" : this.View.Model.GetValue("F_ST_PURORDERBILLNO", e.Row).ToString();
                    string F_ST_SPROWNO = this.View.Model.GetValue("F_ST_SPROWNO", e.Row) == null ? "" : this.View.Model.GetValue("F_ST_SPROWNO", e.Row).ToString();
                    string F_ST_SUPPLYID="";
                    DynamicObject dy_F_ST_SUPPLYID = this.View.Model.GetValue("F_ST_SUPPLYID", e.Row) as DynamicObject;
                    if (dy_F_ST_SUPPLYID == null)
                    { 

                    }
                    else
                    {
                        F_ST_SUPPLYID = dy_F_ST_SUPPLYID["Name"].ToString();
                    }
                    string F_ST_ORIGINALBATCH = this.View.Model.GetValue("F_ST_ORIGINALBATCH", e.Row) == null ? "" : this.View.Model.GetValue("F_ST_ORIGINALBATCH", e.Row).ToString();
                    string batchNumber = F_ST_SALEORDERBILLNO +
                        "\\" + F_ST_PURORDERBILLNO +
                        "\\" + F_ST_SPROWNO +
                        "\\" + F_ST_SUPPLYID +
                        "\\" + F_ST_ORIGINALBATCH;
                    this.View.Model.SetValue("FLOT", batchNumber, e.Row);
                    //this.View.UpdateView("");
                    break;

                case "FMATERIALID":                //物料编码
                    //组织隶属方案和上级部门变化，重新生成部门全称
                    //其中BuildNewFullName为拼接全称函数，此处省略具体实现逻辑
                    //this.Model.SetValue("FFullName", BuildNewFullName(e.Key));
                    //this.View.UpdateView("FFullName");
                    //获取元数据服务
                    IMetaDataService metadataService = Kingdee.BOS.App.ServiceHelper.GetService<IMetaDataService>();
                    //获取物料单据元数据
                    //FormMetadata materialMetadata = metadataService.Load(this.Context,"BD_Material") as FormMetadata;
                    FormMetadata materialMetadata = (FormMetadata)Kingdee.BOS.ServiceHelper.MetaDataServiceHelper.Load(this.View.Context, "BD_MATERIAL");
                    //获取保存服务
                    //ISaveService saveService = Kingdee.BOS.App.ServiceHelper.GetService<ISaveService>();
                    //获取加载数据服务
                    IViewService viewService = Kingdee.BOS.App.ServiceHelper.GetService<IViewService>();
                    DynamicObject material = (DynamicObject)this.Model.GetValue(e.Field);
                    string materialId = Convert.ToString(material["Id"]);


                    DynamicObject[] objs = viewService.Load(
                        this.Context,
                        new object[] { materialId },
                        materialMetadata.BusinessInfo.GetDynamicObjectType());
                    strValue = Convert.ToString(objs[0]["Id"]);
                    //F_st_MaterialNo = "";
                    Entity subEntity = this.View.BillBusinessInfo.GetEntity("FSubEntity");
                    //object obj = this.View.Model.GetEntityDataObject(subEntity).Parent;
                    //F_st_RowNo = 0;
                    break;
            }
            #endregion
        }
        #endregion

        #region AfterBindData-绑定数据后触发
        /// <summary>
        /// 绑定数据后触发
        /// </summary>
        /// <param name="e"></param>
        public override void AfterBindData(EventArgs e)
        {
            base.AfterBindData(e);
            #region
            BusinessInfo info = this.View.OpenParameter.FormMetaData.BusinessInfo;
            Entity resultEntity = info.GetEntity("FSubEntity");
            Entity subEntity = this.View.BillBusinessInfo.GetEntity("FSubEntity");
            DynamicObjectCollection subEntityRows = this.View.Model.GetEntityDataObject(subEntity);
            //删除双数明细的全部行
            subEntityRows.Clear();
            #endregion
        }
        #endregion

        #region EntryCellFocued-单元格聚焦（单击，回车）事件
        /// <summary>
        /// 单据体单元格获取焦点时触发
        /// </summary>
        /// <param name="e"></param>
        public override void EntryCellFocued(EntryCellFocuedEventArgs e)
        {
            base.EntryCellFocued(e);
            #region

            #region
            //获取子单据体对象
            SubEntryEntity t_subEntity = this.View.BusinessInfo.GetEntity("FSubEntity") as SubEntryEntity;
            
            //根据子单据体，获取对应的父单据体
            EntryEntity t_Entity = t_subEntity.ParentEntity;

            //获取父单据体的动态对象集合
            DynamicObjectCollection t_entryRows = this.View.Model.GetEntityDataObject(t_Entity);
            #endregion

            if (e.NewFieldKey.ToUpper() == "F_ST_PAIRQTY")
            {
                DynamicFormShowParameter showParam = new DynamicFormShowParameter();
                //判断子单据双数明细是否有赋值，有赋值，则把当前子单据的数据填入双数明细的子窗体中
                SubEntryEntity subEntity = this.View.BusinessInfo.GetEntity("FSubEntity") as SubEntryEntity;
                EntryEntity Entity = subEntity.ParentEntity;

                //获取父单据体的动态对象集合
                DynamicObjectCollection entryRows = this.View.Model.GetEntityDataObject(Entity);
                DynamicObject currRow = entryRows[e.NewRow];
                // 取当前行的子单据体数据集合
                DynamicObjectCollection subEntityRows = subEntity.DynamicProperty.GetValue(currRow) as DynamicObjectCollection;
                
                //单据名，不能使用继承的单据名，原因未知
                showParam.FormId = "567d468c-e088-44f0-80a0-5e18efea79ee";
                //该单据的主键值，新建时可以不填
                //showParam.PKey = "100001";
                //单据才设置状态，动态表单没有状态
                //showParam.Status = OperationStatus.ADDNEW;
                showParam.ParentPageId = this.View.PageId;
                showParam.OpenStyle.ShowType = ShowType.Floating;
                //showParam.OpenStyle.ShowType = ShowType.InContainer;
                //传递特殊属性到目标模型
                //目标模型可以在其表单插件中的OnInitial事件中获取这些参数
                //传递物料编码
                DynamicObject MATERIAL = currRow["MaterialId"] as DynamicObject; 
                showParam.CustomParams.Add("FMATERIALID", MATERIAL["Id"].ToString());
                showParam.CustomParams.Add("F_st_MaterialNo", MATERIAL["Number"].ToString());
                showParam.CustomParams.Add("F_st_RowNo", (e.NewRow + 1).ToString());
                showParam.CustomComplexParams.Add("SubEntityRows", subEntityRows);

                //获取当前行的数量值
                showParam.CustomParams.Add("PtotalNum", this.Model.GetValue("F_ST_PAIRQTY", e.NewRow).ToString());

                this.View.ShowForm(showParam, r => this.Onclos(r));
            }
            #endregion
        }
        #endregion

        #region Onclos-自定义回调函数，用于把子窗体返回数据给父窗体
        /// <summary>
        /// 回调函数,返回数据
        /// </summary>
        /// <param name="result"></param>
        public void Onclos(FormResult result)
        {
            #region
            PairDetailRtnData pairDetailRtnData = (PairDetailRtnData)result.ReturnData;
            if (pairDetailRtnData != null)
            {
                //单据体
                DynamicObjectCollection docContacts = pairDetailRtnData.DynObjCollection;
                //总双数字段
                int qty = pairDetailRtnData.totalNum;
                //行号
                int row = pairDetailRtnData.rowNum;
                BusinessInfo info = this.View.OpenParameter.FormMetaData.BusinessInfo;

                #region 父单据体字段业务数量赋值

                this.View.Model.SetValue("F_st_PairQty", null, row);

                #endregion

                #region 子单据体双数明细赋值
                //获取当前界面双数明细的单据

                Entity resultEntity = info.GetEntity("FSubEntity");
                //this.View.Model.DeleteEntryData("FSubEntity");
                //this.View.Model.DeleteEntryRow("FSubEntity", 1);
                Entity subEntity = this.View.BillBusinessInfo.GetEntity("FSubEntity");
                DynamicObjectCollection subEntityRows = this.View.Model.GetEntityDataObject(subEntity);
                //删除双数明细的全部行
                subEntityRows.Clear();
                //循环填充子窗体传过来的值
                for (int i = 0; i < docContacts.Count; i++)
                {
                    DynamicObject doc = docContacts[i];
                    DynamicObject bdInfo = doc["F_st_Size"] as DynamicObject;
                    string bdInfo1 = (string)doc["F_st_LR"];
                    decimal bdInfo2 = (decimal)doc["F_st_Qty"];
                    //新建行
                    View.Model.CreateNewEntryRow("FSubEntity");
                    int iRow = View.Model.GetEntryCurrentRowIndex("FSubEntity");
                    View.Model.SetValue("F_ST_SIZE", bdInfo["id"].ToString(), iRow);
                    View.Model.SetValue("F_ST_LR", bdInfo1, iRow);
                    View.Model.SetValue("F_ST_PAIRDETAILQTY", bdInfo2, iRow);

                }
                //给相应的父单据的行的销售数量赋值
                View.Model.SetValue("F_ST_PAIRQTY", qty, row);
                #endregion

                this.View.UpdateView("FSubEntity");
                //this.View.Refresh();
            }
            #endregion
        }
        #endregion

        public override void BeforeF7Select(BeforeF7SelectEventArgs e)
        {
            base.BeforeF7Select(e);

            
        }

    }
}
